// Package sys
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2025 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
// @AutoGenerate Version 2.15.11
package sys

import (
	"context"
	"fmt"
	"hotgo/internal/dao"
	"hotgo/internal/library/contexts"
	"hotgo/internal/library/hgorm"
	"hotgo/internal/library/hgorm/handler"
	"hotgo/internal/library/hgorm/hook"
	"hotgo/internal/model/input/form"
	"hotgo/internal/model/input/sysin"
	"hotgo/internal/service"
	"hotgo/utility/convert"
	"hotgo/utility/excel"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/util/gconv"
)

type sSysOrderVerifyLog struct{}

func NewSysOrderVerifyLog() *sSysOrderVerifyLog {
	return &sSysOrderVerifyLog{}
}

func init() {
	service.RegisterSysOrderVerifyLog(NewSysOrderVerifyLog())
}

// Model 订单核销记录ORM模型
func (s *sSysOrderVerifyLog) Model(ctx context.Context, option ...*handler.Option) *gdb.Model {
	return handler.Model(dao.OrderVerifyLog.Ctx(ctx), option...)
}

// List 获取订单核销记录列表
func (s *sSysOrderVerifyLog) List(ctx context.Context, in *sysin.OrderVerifyLogListInp) (list []*sysin.OrderVerifyLogListModel, totalCount int, err error) {

	list = make([]*sysin.OrderVerifyLogListModel, 0)

	mod := s.Model(ctx, &handler.Option{FilterAuth: false})

	//memberId := contexts.GetUserId(ctx)

	// 字段过滤
	mod = mod.FieldsPrefix(dao.OrderVerifyLog.Table(), sysin.OrderVerifyLogListModel{})
	mod = mod.Fields(hgorm.JoinFields(ctx, sysin.OrderVerifyLogListModel{}, &dao.Order, "order"))
	mod = mod.Fields(hgorm.JoinFields(ctx, sysin.OrderVerifyLogListModel{}, &dao.Store, "store"))
	mod = mod.Fields(hgorm.JoinFields(ctx, sysin.OrderVerifyLogListModel{}, &dao.Product, "product"))
	mod = mod.Fields(hgorm.JoinFields(ctx, sysin.OrderVerifyLogListModel{}, &dao.AdminMember, "adminMember"))

	// 关联表字段
	mod = mod.LeftJoinOnFields(dao.Order.Table(), dao.OrderVerifyLog.Columns().OrderId, "=", dao.Order.Columns().Id)
	mod = mod.LeftJoinOnFields(dao.Store.Table(), dao.OrderVerifyLog.Columns().StoreId, "=", dao.Store.Columns().Id)
	mod = mod.LeftJoinOnFields(dao.Product.Table(), dao.OrderVerifyLog.Columns().ProductId, "=", dao.Product.Columns().Id)
	mod = mod.LeftJoinOnFields(dao.AdminMember.Table(), dao.OrderVerifyLog.Columns().MemberId, "=", dao.AdminMember.Columns().Id)

	// 查询核销时间
	if len(in.CreatedAt) == 2 {
		mod = mod.WhereBetween(dao.OrderVerifyLog.Columns().CreatedAt, in.CreatedAt[0], in.CreatedAt[1])
	}

	// 查询订单UUID
	if in.OrderUid != "" {
		mod = mod.WherePrefixLike(dao.Order.Table(), dao.Order.Columns().Uid, "%"+in.OrderUid+"%")
	}

	// 查询交易ID(流水号)
	if in.OrderTraceId != "" {
		mod = mod.WherePrefixLike(dao.Order.Table(), dao.Order.Columns().TraceId, "%"+in.OrderTraceId+"%")
	}

	// 查询订单类型
	if in.OrderType != "" {
		mod = mod.Where(dao.Order.Table()+"."+dao.Order.Columns().OrderType, in.OrderType)
	}

	// 数据隔离
	//if !service.AdminMember().VerifySuperId(ctx, memberId) && contexts.GetRoleId(ctx) != consts.RoleManage {
	//	mod = mod.Where(dao.OrderVerifyLog.Columns().MemberId, memberId)
	//}

	// 查询门店 id
	if in.StoreId > 0 {
		mod = mod.Where(dao.OrderVerifyLog.Columns().StoreId, in.StoreId)
	}

	// 查询门店名称
	if in.StoreName != "" {
		mod = mod.WherePrefixLike(dao.Store.Table(), dao.Store.Columns().Name, "%"+in.StoreName+"%")
	}

	// 查询门店电话
	if in.StorePhone != "" {
		mod = mod.WherePrefixLike(dao.Store.Table(), dao.Store.Columns().Phone, "%"+in.StorePhone+"%")
	}

	// 查询商品名称
	if in.ProductName != "" {
		mod = mod.WherePrefixLike(dao.Product.Table(), dao.Product.Columns().Name, "%"+in.ProductName+"%")
	}

	// 查询真实姓名
	if in.AdminMemberRealName != "" {
		mod = mod.WherePrefixLike(dao.AdminMember.Table(), dao.AdminMember.Columns().RealName, "%"+in.AdminMemberRealName+"%")
	}

	// 查询手机号码
	if in.AdminMemberMobile != "" {
		mod = mod.WherePrefixLike(dao.AdminMember.Table(), dao.AdminMember.Columns().Mobile, "%"+in.AdminMemberMobile+"%")
	}

	// 分页
	if in.Pagination {
		mod = mod.Page(in.Page, in.PerPage)
	}

	// 排序
	mod = mod.OrderDesc(dao.OrderVerifyLog.Table() + "." + dao.OrderVerifyLog.Columns().Id)

	// 查询数据
	if err = mod.Hook(hook.MemberSummary).ScanAndCount(&list, &totalCount, false); err != nil {
		err = gerror.Wrap(err, "获取订单核销记录列表失败，请稍后重试！")
		return
	}
	return
}

// Export 导出订单核销记录
func (s *sSysOrderVerifyLog) Export(ctx context.Context, in *sysin.OrderVerifyLogListInp) (err error) {
	list, totalCount, err := s.List(ctx, in)
	if err != nil {
		return
	}

	// 字段的排序是依据tags的字段顺序，如果你不想使用默认的排序方式，可以直接定义 tags = []string{"字段名称", "字段名称2", ...}
	tags, err := convert.GetEntityDescTags(sysin.OrderVerifyLogExportModel{})
	if err != nil {
		return
	}

	var (
		fileName  = "导出订单核销记录-" + gctx.CtxId(ctx)
		sheetName = fmt.Sprintf("索引条件共%v行,共%v页,当前导出是第%v页,本页共%v行", totalCount, form.CalPageCount(totalCount, in.PerPage), in.Page, len(list))
		exports   []sysin.OrderVerifyLogExportModel
	)

	if err = gconv.Scan(list, &exports); err != nil {
		return
	}

	err = excel.ExportByStructs(ctx, tags, exports, fileName, sheetName)
	return
}

// Edit 修改/新增订单核销记录
func (s *sSysOrderVerifyLog) Edit(ctx context.Context, in *sysin.OrderVerifyLogEditInp) (err error) {
	return g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {

		// 修改
		if in.Id > 0 {
			if _, err = s.Model(ctx).
				Fields(sysin.OrderVerifyLogUpdateFields{}).
				WherePri(in.Id).Data(in).Update(); err != nil {
				err = gerror.Wrap(err, "修改订单核销记录失败，请稍后重试！")
			}
			return
		}

		// 新增
		in.CreatedBy = uint64(contexts.GetUserId(ctx))
		if _, err = s.Model(ctx, &handler.Option{FilterAuth: false}).
			Fields(sysin.OrderVerifyLogInsertFields{}).
			Data(in).OmitEmptyData().Insert(); err != nil {
			err = gerror.Wrap(err, "新增订单核销记录失败，请稍后重试！")
		}
		return
	})
}

// Delete 删除订单核销记录
func (s *sSysOrderVerifyLog) Delete(ctx context.Context, in *sysin.OrderVerifyLogDeleteInp) (err error) {

	if _, err = s.Model(ctx).WherePri(in.Id).Unscoped().Delete(); err != nil {
		err = gerror.Wrap(err, "删除订单核销记录失败，请稍后重试！")
		return
	}
	return
}

// View 获取订单核销记录指定信息
func (s *sSysOrderVerifyLog) View(ctx context.Context, in *sysin.OrderVerifyLogViewInp) (res *sysin.OrderVerifyLogViewModel, err error) {
	if err = s.Model(ctx).WherePri(in.Id).Hook(hook.MemberSummary).Scan(&res); err != nil {
		err = gerror.Wrap(err, "获取订单核销记录信息，请稍后重试！")
		return
	}
	return
}
